//
//  MTWebPayViewController.m
//  MeToo
//
//  Created by 俊松何 on 2018/7/25.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "MTWebPayViewController.h"
#import <WebKit/WebKit.h>
#import "RegExCategories.h"

@interface MTWebPayViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property(nonatomic,strong) WKWebView *wkwebView;
@property (nonatomic ,strong)WKUserContentController * userCC;
@property(nonatomic,strong) UIProgressView *progressView;
@property(nonatomic,assign) BOOL isPay;

@end

@implementation MTWebPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeUI];
}
-(void)makeUI
{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = YES;
    config.mediaPlaybackRequiresUserAction = false;
    _wkwebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    _wkwebView.scrollView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
    
    _wkwebView.navigationDelegate = self;
    _wkwebView.UIDelegate = self;
    _progressView = [[UIProgressView alloc] init];
    [self.view addSubview:_wkwebView];
    [self.view addSubview:_progressView];
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
    }];
    [_wkwebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [_wkwebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self.wkwebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSString *oldAgent = result;
        if(![oldAgent containsString:@"mitu/"])
        {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString  *extuserAgent =  [NSString stringWithFormat:@"mitu/%@",[infoDictionary objectForKey:@"CFBundleShortVersionString"]];
            // 给User-Agent添加额外的信息
            NSString *newAgent = [NSString stringWithFormat:@"%@ %@", oldAgent, extuserAgent];
            NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
            [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self.wkwebView setCustomUserAgent:newAgent];
        }
        NSURL *url = [[NSURL alloc] initWithString:self.payModel.h5PayUrl];
        NSURLRequest *requst = [[NSURLRequest alloc] initWithURL:url];
        [self.wkwebView loadRequest:requst];
        [self.wkwebView loadRequest:requst];
        
    }];
    self.userCC = config.userContentController;
    [self.userCC addScriptMessageHandler:self name:@"callFunc"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backAppClick) name:@"applicationWillEnterForeground" object:nil];
}

-(void)backAppClick
{
    if(_isPay)
    {
        NSURL *url = [[NSURL alloc] initWithString:_payModel.queryResultUrl];
        NSURLRequest *requst = [[NSURLRequest alloc] initWithURL:url];
        [_wkwebView loadRequest:requst];
    }
}


-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"%@",message.body);
    if([message.body isKindOfClass:[NSString class]])
    {
        if([message.body isEqualToString:@"MT://prepay/success"])
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    // 返回页面的时候取消监听
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        self.progressView.progress = self.wkwebView.estimatedProgress;
        if (self.progressView.progress == 1)
        {
            self.progressView.hidden = YES;
        }else
        {
            self.progressView.hidden = NO;
        }
    }else if ([keyPath isEqualToString:@"title"])
    {
        self.title = self.wkwebView.title;
    }
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *url = navigationAction.request.URL;
    NSString *urlString = (url) ? url.absoluteString : @"";
    
    NSLog(@"%@",url.absoluteString);
    
    // iTunes: App Store link
    if ([urlString isMatch:RX(@"\\/\\/itunes\\.apple\\.com\\/")]) {
        
        [[UIApplication sharedApplication] openURL:url];
        //        [self.navigationController popViewControllerAnimated:NO];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    // Protocol/URL-Scheme without http(s)
    else if (![urlString isMatch:[@"^https?:\\/\\/." toRxIgnoreCase:YES]]) {
        NSString *newStr =  [url.absoluteString stringByReplacingOccurrencesOfString:@"alipays" withString:@"h5pay.mmcoco.com"];
        NSURL *newUrl = [NSURL URLWithString:newStr];
        [[UIApplication sharedApplication] openURL:newUrl];
        self.isPay = YES;
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (NSString *)URLEncodedString:(NSString *)url
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = url;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

/**
 *  URLDecode
 */
-(NSString *)URLDecodedString:(NSString *)url
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *encodedString = url;
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

@end
